﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using ywxt.Common;

namespace ZJK
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            //WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

        }

        void Application_End(object sender, EventArgs e)
        {
            //在应用程序关闭时运行的代码        
        }

        protected void Application_AuthenticateRequest()
        {
            //判断正在请求页的用户的身份验证信息是否为空
            if (HttpContext.Current.User != null)
            {
                //判断用户是否已经进行了身份验证
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    //判断当前用户身份验证的方式是否为Forms身份验证方式
                    if (HttpContext.Current.User.Identity is FormsIdentity)
                    {
                        //获得进行了Forms身份验证的用户标识
                        FormsIdentity UserIdent = (FormsIdentity)(HttpContext.Current.User.Identity);
                        //从身份验证票中获得用户数据
                        string UserData = UserIdent.Ticket.UserData;

                        //从用户数据中反序列化用户信息
                        AuthenticatedUser user =
                            Newtonsoft.Json.JsonConvert.DeserializeObject<AuthenticatedUser>(UserData);

                        //分割用户角色数据得到用户角色列表
                        string[] roles = user.RoleGroups.ToArray();

                        //从用户标识和角色组初始化GenericPrincipal类
                        HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(UserIdent, roles);
                    }
                }
            }
        }

    }
}